<template>
  <div class="machine full-height bg-white page-content content relative-position" style="padding-bottom: 72px">
    <!-- 搜索区 -->
    <collapse ref="collapse">
      <template v-slot:content>
        <div class="form-inline bottom" style="justify-content: space-between; padding: 6px 20px 0;">
          <div class="left box" style="display: flex">
            <div class="row">
              <select-tree label="位置" :sel-tree="queryParams.location" class="margin-r-15 margin-b-20" ref="selectTree"
                           :tree-list="locationOptions" node-key="hash" @treeChange="_changeTreeNode"/>
              <q-select
                class="select margin-r-15 margin-b-20"
                outlined dense emit-value map-options options-dense
                :options="stationOptions"
                v-model="queryParams.station"
              >
                <template v-slot:no-option>
                  <div class="no-option"/>
                </template>
                <template v-slot:before>
                  <span class="form-name">工位:</span>
                </template>
              </q-select>
              <q-select
                class="select margin-r-15 margin-b-20"
                outlined dense emit-value map-options options-dense
                :options="statusOptions"
                v-model="queryParams.status"
              >
                <template v-slot:no-option>
                  <div class="no-option"/>
                </template>
                <template v-slot:before>
                  <span class="form-name">状态:</span>
                </template>
              </q-select>
            </div>
          </div>
          <div style="display: flex">
            <q-btn
              class="btn margin-r-10"
              outline
              color="primary"
              @click="resetSearch"
              label="重置"
            />
            <q-btn class="btn" unelevated type="submit" color="primary" label="查询" @click="pagination.page = 1; pagination.rowsPerPage = 15; searchList()"/>
          </div>
        </div>
        <div class="form-inline bottom" style="justify-content: flex-end" :style="displayMode == 'list'?'padding:0 20px':'padding:0 20px 20px'">
          <div class="right box flex">
            <select-input ref="selectInput" :list="searchCondition" @search="inputSearch" @clearSearchVal="clearSearchVal"/>
            <q-btn flat round color="primary" @click="changeDisplay()" :icon="displayMode == 'list' ? 'iconfont icontubiao-57': 'iconfont icontubiao-104'" class="margin-l-10" style="min-width: 32px;width: 32px" />
          </div>
        </div>
      </template>
    </collapse>
    <!-- 搜索区End -->
    <!-- 卡片列表 -->
    <q-scroll-area ref="scrollTargetRef" style="margin: 0 10px;flex: 1;" :thumb-style="thumbStyle" v-show="displayMode == 'list'">
      <q-infinite-scroll :offset="250" :scroll-target="$refs.scrollTargetRef"  ref="scrollTarget">
        <div class="row flex">
          <div class="card-item col-lg-3 col-md-4 col-sm-6" v-for="(item, index) in tableData" :key="index">
            <div style="padding: 0 5px">
              <div class="card" @click="routerTo(item)"
                   v-stat="{id:CommonConfig.statData.machine.detail.id,name:CommonConfig.statData.machine.detail.name}">
                <div class="flex items-center justify-between" style="display:-webkit-flex;display:flex">
                  <div class="flex items-center" style="width: calc(100% - 125px)">
                    <div class="device-name font-size-16 text-ellipsis" style="width: 100px">
                      {{ item.name && item.assetNumber ? `${item.name}(${item.assetNumber})` : '--' }}
                      <q-tooltip>{{ item.name && item.assetNumber ? `${item.name}(${item.assetNumber})` : '--' }}</q-tooltip>
                    </div>
                    <div class="warning text-white" v-show="item.news > 0">
                      <q-icon class="iconfont icontubiao-78 font-size-12" style="margin-right: 5px;vertical-align: top"></q-icon>
                      <span style="line-height: 22px">{{ item.news > 99 ? '99+' : item.news }}</span>
                    </div>
                  </div>
                  <div class="time-box text-center text-white" :style="{ backgroundColor: judgeStatus(item.status, 'color') }">
                    {{ `${judgeStatus(item.status, 'name')}:${item.statusDuration}${item.statusDurationUnit}` }}
                  </div>
                </div>
                <div class="flex items-center justify-between bor-b" style="line-height: 250%">
                  <div>操作员：{{ item.operatorName ? item.operatorName : '--' }}</div>
                  <div>技术员：{{ item.technicianName ? item.technicianName : '--' }}</div>
                </div>
                <div class="bor-b" style="line-height: 250%">
                  {{ `${item.model || '--'}(${item.ncType || '--'})`}}
                </div>
                <div style="line-height: 1.7;margin-top: 5px; width: 100%" class="text-ellipsis">加工产品：
                  {{`${item.materialName || '--'}/${item.processName ? item.processSort + 1 + '-' : ''}${item.processName || '--'}`}}
                  <q-tooltip>{{`${item.materialName || '--'}/${item.processName ? item.processSort + 1 + '-' : ''}${item.processName || '--'}`}}
                  </q-tooltip>
                </div>
                <div style="line-height: 1.7">当前程序：{{item.programName}} （{{item.programNo}}/{{item.programPart}}）</div>

                <div style="line-height: 1.7" class="flex items-center justify-between">
                  <div>计划进度：{{ `${item.finishedCount}/${item.jobCount}` }}</div>
                  <div>
                    {{ getDifferenceCount(item.expectedCount, item.finishedCount, item.jobCount).label }}
                    {{ getDifferenceCount(item.expectedCount, item.finishedCount, item.jobCount).value}}
                  </div>
                </div>
                <div class="progress-bar">
                  <div class="progress-detail" :style="{width: `${item.actualProgress}%`}"></div>
                  <div class="tips" :style="{ left: `${ item.progress }%` }"></div>
                </div>
              </div>
            </div>
            <div class="card-tips flex items-center">
              <img src="statics/img/screw.png">
              <span class="text-ellipsis text-center font-size-16"><q-icon class="iconfont icontubiao-141 font-size-12" style="margin-right: 5px;vertical-align: top"></q-icon>{{ item.opNum ? item.opNum : '—'}} - {{ item.opName ? item.opName : '—'}}</span>
              <img src="statics/img/screw.png">
            </div>
          </div>
        </div>
      </q-infinite-scroll>
    </q-scroll-area>
    <!-- 卡片列表End -->
    <!-- table -->
    <q-table
      :data="tableData" :columns="tableColumns"
      row-key="id" class="myTable scroll"
      :pagination.sync="pagination" hide-bottom
      no-data-label="暂无数据"
      color="primary"
      v-show="displayMode == 'table'"
    >
      <template v-slot:body="props">
        <q-tr :props="props" style="cursor:pointer" @click="routerTo(props.row)" v-stat="{id:'dlp0702',name:'详情'}">
          <q-td :props="props" key="opName">{{ props.row.opNum ? props.row.opNum : '—'}} - {{ props.row.opName ? props.row.opName : '—'}}</q-td>
          <q-td :props="props" key="name">
            {{ props.row.name && props.row.assetNumber ? `${props.row.name}(${props.row.assetNumber})` : '—' }}
          </q-td>
          <q-td :props="props" key="status">
            <div
              class="status"
              :style="{ backgroundColor:judgeStatus(props.row.status, 'color') }"
            />
            <span>{{ judgeStatus(props.row.status, 'name') }}</span>
          </q-td>
          <q-td :props="props" key="news">
            <div class="warning text-white" style="display: inline;" v-show="props.row.news > 0">
              <q-icon class="iconfont icontubiao-78 font-size-12" style="margin-right: 5px;vertical-align: top"></q-icon>
              <span style="line-height: 22px">{{props.row.news > 99?'99+':props.row.news}}</span>
            </div>
            <div v-show="props.row.news == 0">--</div>
          </q-td>
          <q-td :props="props" key="materialName">
            {{`${props.row.materialName || '--'}/${props.row.processName ? props.row.processSort + 1 + '-' : ''}${props.row.processName || '--'}`}}
          </q-td>
          <q-td :props="props" key="progress" style="min-width: 250px">
            <div class="progress-bar">
              <div class="progress-detail" :style="{width: `${props.row.actualProgress}%`}"></div>
              <div class="tips" :style="{ left: `${props.row.progress}%` }"></div>
            </div>
            <span>
                计划进度：{{ `${props.row.finishedCount}/${props.row.jobCount}` }}
                {{ getDifferenceCount(props.row.expectedCount, props.row.finishedCount, props.row.jobCount).label }}
                {{ getDifferenceCount(props.row.expectedCount, props.row.finishedCount, props.row.jobCount).value}}
            </span>
          </q-td>
          <q-td :props="props" key="programNo">
            {{props.row.programName}} （{{props.row.programNo}}/{{props.row.programPart}}）
          </q-td>
          <q-td :props="props" key="operatorName">
            {{props.row.operatorName ? props.row.operatorName : '--'}}
          </q-td>
          <q-td :props="props" key="technicianName">
            {{props.row.technicianName ? props.row.technicianName : '--'}}
          </q-td>
        </q-tr>
      </template>
    </q-table>
    <!-- table End -->
    <!--&lt;!&ndash; 搜索区End &ndash;&gt;-->
    <!--<pagination-->
      <!--style="padding-bottom: 30px"-->
      <!--v-model="pagination.page"-->
      <!--:page-size="pagination.rowsPerPage"-->
      <!--:total="pagination.rowsNumber"-->
      <!--@changePage="onPageChange"-->
      <!--@changePageSize="onPageSizeChange">-->
    <!--</pagination>-->
  </div>
</template>

<script>

import SelectInput from '../../components/select-input/index'
import Collapse from '../../components/collapse/index'
// import Pagination from '../../components/pagination/index'
import SelectTree from 'src/components/select-tree'
import { getOrganize, getStation, getMachineStatus, getProcessCount } from 'src/boot/status/machine'
import { defaultSchemesClearer } from '../../assets/js/util'
import { getDict } from '../../boot/common/dict'
import { mapGetters } from 'vuex'
import refreshMixin from '../../assets/js/refresh-mixin'

export default {
  name: 'machine',
  mixins: [refreshMixin],
  computed: {
    ...mapGetters([
      'userInfo'
    ])
  },
  components: {
    SelectInput,
    Collapse,
    // Pagination,
    SelectTree
  },
  data () {
    return {
      // 滚动条样式
      thumbStyle: this.CommonConfig.thumbStyle,
      // 列表初始化显示方式
      displayMode: 'list',
      // 搜索条件
      searchCondition: [
        { id: 'number', name: '设备编号', statId: this.CommonConfig.statData.machine.searchByMachineNum.id },
        { id: 'name', name: '设备名称', statId: this.CommonConfig.statData.machine.searchByMachineName.id },
        { id: 'manufacturer', name: '设备型号', statId: this.CommonConfig.statData.machine.searchByMachineModel.id },
        { id: 'technician', name: '数控类型', statId: this.CommonConfig.statData.machine.searchByMachineType.id }
      ],
      // 表格列
      tableColumns: [
        { name: 'opName', field: 'opName', label: '工位', align: 'left' },
        { name: 'name', field: 'name', label: '设备名称', align: 'left' },
        { name: 'status', field: 'status', label: '设备状态', align: 'left' },
        { name: 'news', field: 'news', label: '报警数', align: 'left' },
        { name: 'materialName', field: 'materialName', label: '产品名称', align: 'left' },
        { name: 'progress', field: 'progress', label: '计划进度', align: 'left' },
        { name: 'programNo', field: 'programNo', label: '当前程序', align: 'left' },
        { name: 'operatorName', field: 'operatorName', label: '操作员', align: 'left' },
        { name: 'technicianName', field: 'technicianName', label: '技术员', align: 'left' }
      ],
      // 搜索条件
      searchBy: '',
      // 搜索值
      keyword: '',
      // 主表格分页配置
      pagination: {
        // 当前页码
        page: 1,
        // 每页条数
        rowsPerPage: 15,
        // 总条数
        rowsNumber: 0
      },
      // 所在位置数据源
      locationOptions: [],
      // 工位数据源
      stationOptions: [],
      // 状态源数据
      statusOptions: [],
      // 查询条件
      queryParams: {
        location: {
          id: null,
          level: null,
          label: '',
          hash: ''
        }, // 所在位置
        station: null,
        status: null
      },
      // 列表数据
      tableData: [],
      //  mqtt实例
      client: null,
      // 前一页的boxId数组用于取消订阅
      oldBoxId: [],
      // mqtt定时器
      // timerMqtt: null,
      // 查询定时器
      timerGetList: null,
      // loading定时器
      timerLoading: null,
      timerTime: null,
      duration: 0
    }
  },

  created () {
    // 初始化查询列表
    this.init()
    // 初始化mqtt
    this.initMqtt()
  },

  mounted () {
    // 每60秒重新订阅一次mqtt防止订阅失效
    // this.timerMqtt = setInterval(this.onConnect, 60000)
    // 每3分钟重新查询列表以更新应完成产量
    this.timerGetList = setInterval(this.searchList, 300000)
    this.timerTime = setInterval(this.updateDuration, 2000)
  },

  beforeDestroy () {
    // 清除定时器
    clearInterval(this.timer)
    clearInterval(this.timerGetList)
    if (this.timerLoading !== void 0) {
      clearTimeout(this.timerLoading)
      this.$q.loading.hide()
    }
    clearInterval(this.timerTime)
    // 取消订阅
    this.closeUbscribeTopic()
    // 关闭连接
    this.client.disconnect()
  },

  methods: {
    /**
     * 全局刷新数据
     * author: xueli
     */
    refreshInfo () {
      // 清除定时器
      clearInterval(this.timer)
      clearInterval(this.timerGetList)
      if (this.timerLoading !== void 0) {
        clearTimeout(this.timerLoading)
        this.$q.loading.hide()
      }
      clearInterval(this.timerTime)
      // 取消订阅
      this.closeUbscribeTopic()
      // 关闭连接
      this.client.disconnect()

      this.resetSearch()
      this.pagination.page = 1
      this.pagination.rowsPerPage = 15
      // 初始化查询列表
      this.init()
      // 初始化mqtt
      this.initMqtt()
      // 展示方式为list
      this.displayMode = 'list'
      this.$refs.collapse.isActive = true
      // 清空搜索值
      this.$refs.selectInput.clearSearchVal()
      // 每60秒重新订阅一次mqtt防止订阅失效
      // this.timerMqtt = setInterval(this.onConnect, 60000)
      // 每3分钟重新查询列表以更新应完成产量
      this.timerGetList = setInterval(this.searchList, 300000)
      this.timerTime = setInterval(this.updateDuration, 2000)
    },

    /**
     * FIXME 有工具函数，迭代重构时记得直接调用工具函数
     * 时分秒转换
     * @param {number} second
     * @return {{}}
     */
    getDuration (second) {
      if (second > 0 && second < 60) {
        let seconds = second
        return {
          duration: seconds,
          unit: '秒'
        }
      } else if (second >= 60 && second < 3600) {
        let minutes = Math.floor(parseInt(second) / 60)
        return {
          duration: minutes,
          unit: '分'
        }
      } else if (second >= 3600 && second < (3600 * 24)) {
        let hours = Math.floor(parseInt(second) / 3600)
        return {
          duration: hours,
          unit: '时'
        }
      } else {
        let days = Math.floor(parseInt(second) / (3600 * 24))
        return {
          duration: days,
          unit: '天'
        }
      }
    },

    /**
     * 获取实际预计差值
     * @param {number} expectedCount 预计完成数量
     * @param {number} finishedCount 实际完成数量
     * @param {number} jobCount 总计划数
     * @return {{}}
     */
    getDifferenceCount (expectedCount, finishedCount, jobCount) {
      let label = ''
      let value = null
      // 若预计产量大于总数
      // 返回总数-预计的绝对值
      if (parseInt(expectedCount) > parseInt(jobCount)) {
        (parseInt(jobCount) - parseInt(finishedCount)) > 0 ? label = '落后数：' : label = '领先数：'
        value = Math.abs(parseInt(jobCount) - parseInt(finishedCount))
      } else {
        // 若预计产量小于总数
        // 返回预计-实际的绝对值
        (parseInt(expectedCount) - parseInt(finishedCount)) > 0 ? label = '落后数：' : label = '领先数：'
        value = Math.abs(parseInt(expectedCount) - parseInt(finishedCount))
      }

      return {
        value: value,
        label: label
      }
    },

    /**
     * FIXME 现在是按定时器每秒增加 应改为当前时间-开始时间
     * 计时器，用来增加每种状态秒数
     */
    updateDuration () {
      this.tableData.forEach(o => {
        o.oldSecond = parseInt(o.oldSecond) + 1
        o.statusDuration = this.getDuration(o.oldSecond).duration
        o.statusDurationUnit = this.getDuration(o.oldSecond).unit
      })
    },

    /**
     * 初始化数据
     */
    init () {
      this.statusOptions = [{
        label: '全部',
        value: null
      }]

      // 冲状态枚举中取出机场状态数组
      const newArr = Object.entries(this.Enums.MACHINES_STATUS)
        .map(entry => {
          return {
            value: entry[1].value,
            label: entry[1].desc,
            color: entry[1].color
          }
        })
      this.statusOptions.push(...newArr)

      this.locationOptions = []
      this.equipmentTypeOptions = []
      // 获取组织机构树
      getOrganize().then(res => {
        // 去除 default 节点
        let clearTree = defaultSchemesClearer.clear(res.data)

        // 重新组织 tree
        clearTree.forEach(reorganize)

        function reorganize (node) {
          // 如果当前节点是工位，将 opname 挪到 label
          if (node.level === 5) {
            node.label = node.opname
          }

          // 为节点添加唯一键，用于 tree 组件标识唯一节点
          node.uniqueKey = node.level + ':' + node.id

          if (node.children instanceof Array) {
            node.children.forEach(reorganize)
          }
        }

        this.locationOptions = clearTree
        this.queryParams.location = Object.assign({}, clearTree[0])

        this.$refs.selectTree.setValue(this.queryParams.location)

        this._changeTreeNode(this.queryParams.location)

        this.searchList()
      })
      // 获取机床类型
      getDict('machine_type', false).then(res => {
        this.equipmentTypeOptions = res.data
      })
    },

    /**
     * 初始化mqtt
     */
    initMqtt () {
      console.log(this.CommonConfig.mqttConfig.MQTT_SERVICE)
      // 生成一个唯一的userId用于连接盒子，此id必须唯一
      const userId = 'webClient' + this.userInfo.user_id.toString() + Date.parse(new Date()).toString()
      // 创建mq实例
      this.client = new window.Paho.MQTT.Client(
        this.CommonConfig.mqttConfig.MQTT_SERVICE,
        Number(this.CommonConfig.mqttConfig.MQRR_PORT),
        userId)
      // 连接服务器并注册连接成功处理事件
      this.client.connect({ onSuccess: this.onConnect })
      // 注册连接断开处理事件
      this.client.onConnectionLost = this.onConnectionLost
      // 注册消息接收处理事件
      this.client.onMessageArrived = this.onMessageArrived
    },

    /**
     * 订阅并发送消息
     */
    onConnect () {
      console.log('连接成功')
      this.tableData.forEach(o => {
        this.client.subscribe(
          `${this.CommonConfig.mqttConfig.MQTT_TOPIC.statusTopic.subscribeTopic}${o.boxId}`, { qos: 1 }
        )// 订阅主题（机床状态）
        this.client.subscribe(
          `${this.CommonConfig.mqttConfig.MQTT_TOPIC.productivityTopic.subscribeTopic}${o.boxId}`, { qos: 1 }
        )// 订阅主题（产量相关）
        this.client.subscribe(
          `${this.CommonConfig.mqttConfig.MQTT_TOPIC.programName.subscribeTopic}${o.boxId}`, { qos: 1 }
        )// 订阅主题（程序名称）
        this.client.subscribe(
          `${this.CommonConfig.mqttConfig.MQTT_TOPIC.processCount.subscribeTopic}${o.boxId}`, { qos: 1 }
        )// 订阅主题（单次加工循环数量）
        this.client.subscribe(
          `${this.CommonConfig.mqttConfig.MQTT_TOPIC.productivity.subscribeTopic}${o.boxId}`, { qos: 1 }
        )// 订阅主题（循环次数）
      })
    },

    /**
     * 接受盒子返回消息
     * @param {string} message
     */
    onMessageArrived (message) {
      // 分割topic
      let msgBoxIds = message.destinationName.split('/')
      // 序列化返回msg
      let msg = JSON.parse(message.payloadString)
      console.log(msg, '序列化的消息')
      // 获取boxId
      let msgBoxId = msgBoxIds[4]
      // 判断返回的msg是否为状态的msg
      // 状态相关
      if (msgBoxIds[3] === 'status') {
        if (msg.alarmCount !== null && msg.alarmCount !== undefined) {
          this.tableData.forEach(o => {
            if (o.boxId === msgBoxId) {
              o.news = msg.alarmCount
            }
          })
        }
        this.tableData.forEach(o => {
          if (o.boxId === msgBoxId) {
            // 1加工
            if (msg.statusCode !== this.Enums.MACHINES_STATUS.WARNING.value) {
              o.oldSecond = parseInt(msg.duration)
              o.statusDuration = this.getDuration(o.oldSecond).duration
              o.statusDurationUnit = this.getDuration(o.oldSecond).unit
              // 非加工状态 单次加工循环数量清零
              if (msg.statusCode !== this.Enums.MACHINES_STATUS.MACHINING.value) {
                o.oneCycleCount = 0
              } else {
                // 当切换为加工状态时（并且前次状态不为加工状态）
                if (o.status !== this.Enums.MACHINES_STATUS.MACHINING.value) {
                  // 请求后台，获取单次加工循环数量
                  getProcessCount(o.boxId, o.id).then(res => {
                    o.oneCycleCount = res.data.oneCycleCount
                  })
                }
              }
              o.status = msg.statusCode
            }
          }
        })
      } else if (msgBoxIds[3] === 'programName') {
        // 程序名称
        this.tableData.forEach(o => {
          if (o.boxId === msgBoxId) {
            o.programName = msg.ProgramName
          }
        })
      } else if (msgBoxIds[3] === 'processCount') {
        // 单次加工循环数量(接收及覆盖)
        this.tableData.forEach(o => {
          if (o.boxId === msgBoxId) {
            o.oneCycleCount = msg.oneCycleCount
            o.finishedCount = msg.oneCycleCount * o.productivity
          }
        })
      } else if (msgBoxIds[3] === 'productivity') {
        // 循环次数(接收及覆盖)
        this.tableData.forEach(o => {
          if (o.boxId === msgBoxId) {
            o.productivity = msg.productivity
            // 计算实际完工
            o.finishedCount = msg.productivity * o.oneCycleCount

            if (parseInt(o.expectedCount) / parseInt(o.jobCount) * 100 <= 0) {
              o.progress = 0
            } else if (parseInt(o.expectedCount) / parseInt(o.jobCount) * 100 >= 100) {
              o.progress = 100
            } else {
              o.progress = parseInt(o.expectedCount) / parseInt(o.jobCount) * 100
            }

            if (parseInt(o.finishedCount) / parseInt(o.jobCount) * 100 <= 0) {
              o.actualProgress = 0
            } else if (parseInt(o.finishedCount) / parseInt(o.jobCount) * 100 >= 100) {
              o.actualProgress = 100
            } else {
              o.actualProgress = parseInt(o.finishedCount) / parseInt(o.jobCount) * 100
            }
          }
        })
      }
    },

    /**
     * 连接丢失
     * @param {{}} responseObject
     */
    onConnectionLost (responseObject) {
      console.log('机台状态列表，连接断开事件')
      if (responseObject.errorCode !== 0) {
        this.onConnect()
        console.log('onConnectionLost:' + responseObject.errorMessage)
        console.log('连接已断开')
      }
    },

    /**
     * 取消订阅
     */
    closeUbscribeTopic () {
      this.oldBoxId.forEach(o => {
        this.client.unsubscribe(`${this.CommonConfig.mqttConfig.MQTT_TOPIC.statusTopic.subscribeTopic}${o.boxId}`)
        this.client.unsubscribe(`${this.CommonConfig.mqttConfig.MQTT_TOPIC.productivityTopic.subscribeTopic}${o.boxId}`)
      })
    },

    /**
     * 切换展现形式
     */
    changeDisplay () {
      this.displayMode = (this.displayMode === 'list' ? 'table' : 'list')
    },

    /**
     * 清空搜索值
     */
    clearSearchVal () {
      this.pagination.page = 1
      this.pagination.rowsPerPage = 15
      this.keyword = ''
      this.searchBy = ''
      this.searchList()
    },

    /**
     * 模糊查询
     * @param {string} item
     * @param {string} searchVal
     */
    inputSearch (item, searchVal) {
      this.pagination.page = 1
      this.pagination.rowsPerPage = 15
      this.keyword = searchVal
      this.searchBy = item.id
      this.searchList()
    },

    /**
     * 重置查询条件
     */
    resetSearch () {
      this.queryParams.location = Object.assign({}, this.locationOptions[0])
      this.$refs.selectTree.setValue(this.queryParams.location)
      // this.queryParams.location.id = null
      // this.queryParams.location.level = null
      // this.queryParams.location.label = ''
      // this.queryParams.location.hash = ''
      // this.queryParams.station = null
      this._changeTreeNode(this.queryParams.location)
      this.queryParams.status = null
    },

    /**
     * 根据条件搜索
     */
    searchList () {
      console.log(this.queryParams.location, 777777)
      this.$q.loading.show()

      // hiding in 2s
      this.timerLoading = setTimeout(() => {
        this.$q.loading.hide()
        this.timerLoading = void 0
      }, 500)
      getMachineStatus(
        this.keyword,
        this.pagination.page,
        this.pagination.rowsPerPage,
        this.searchBy,
        this.queryParams.status,
        this.queryParams.station,
        this.queryParams.location.id,
        this.queryParams.location.level
      ).then(res => {
        res.data.list.forEach(o => {
          if (parseInt(o.expectedCount) / parseInt(o.jobCount) * 100 <= 0) {
            o.progress = 0
          } else if (parseInt(o.expectedCount) / parseInt(o.jobCount) * 100 >= 100) {
            o.progress = 100
          } else {
            o.progress = parseInt(o.expectedCount) / parseInt(o.jobCount) * 100
          }

          if (parseInt(o.finishedCount) / parseInt(o.jobCount) * 100 <= 0) {
            o.actualProgress = 0
          } else if (parseInt(o.finishedCount) / parseInt(o.jobCount) * 100 >= 100) {
            o.actualProgress = 100
          } else {
            o.actualProgress = parseInt(o.finishedCount) / parseInt(o.jobCount) * 100
          }
          o.oldSecond = parseInt(o.statusDuration)
          o.statusDuration = this.getDuration(o.oldSecond).duration
          o.statusDurationUnit = this.getDuration(o.oldSecond).unit
        })
        this.tableData = res.data.list
        this.pagination.rowsNumber = res.data.total
      }).then(() => {
        this.closeUbscribeTopic()
        this.onConnect()
        this.oldBoxId = []
        this.oldBoxId = this.tableData.map(item => { return item.boxId })
      })
    },

    /**
     * 选择组织机构树节点
     * @param {number} val
     */
    _changeTreeNode: function (val) {
      if (val.id && val.label && val.hash) {
        this.queryParams.location.id = val.id
        this.queryParams.location.level = val.level
        this.queryParams.location.label = val.label
        this.queryParams.location.hash = val.hash
        this.queryParams.station = ''
        this.stationOptions = [{
          value: null,
          label: '全部'
        }]
        // 获取工位
        getStation(val.level, val.id).then(res => {
          if (res.data.list.length > 0) {
            for (const i of res.data.list) {
              if (res.data.list.length !== 0) {
                this.stationOptions.push({
                  value: i['id'],
                  label: i['opdesc']
                })
              }
            }
          }
        })

        // 默认选择第一个工位
        this.queryParams.station = this.stationOptions[0].value
      } else {
        this.queryParams.location = {
          id: null,
          level: null,
          label: '',
          hash: ''
        }
        this.queryParams.station = null
        this.stationOptions = []
      }
    },

    /**
     * 切换每夜显示条数
     * @param {number} val
     */
    onPageSizeChange: function (val) {
      this.pagination.rowsPerPage = val
      this.searchList()
    },

    /**
     * 切换页码
     * @param {number} val
     */
    onPageChange: function (val) {
      this.pagination.page = val
      this.searchList()
    },

    /**
     * 过滤状态枚举
     * @param {number} statusCode
     * @param {string} type
     * @return {string}
     */
    judgeStatus (statusCode, type) {
      if (type === 'name') {
        let name = ''
        this.statusOptions.forEach(o => {
          if (o.value === statusCode) {
            name = o.label
          }
        })
        return name
      } else {
        let color = ''
        this.statusOptions.forEach(o => {
          if (o.value === statusCode) {
            color = o.color
          }
        })
        return color
      }
    },

    /**
     * 跳转详情传值
     * @param {{}} val
     */
    routerTo (val) {
      this.$router.push({
        path: '/main/status/machine/machine-detail',
        query: {
          params: JSON.stringify(val)
        }
      })
    }
  }
}
</script>

<style scoped lang="stylus">
  .font-size-16 {
    font-size 16px
  }
  .font-size-14 {
    font-size 14px
  }
  .font-size-12 {
    font-size 12px
  }
  /deep/ .q-select__dropdown-icon {
    width 24px
    height 24px
    font-size 24px
    color rgba(0, 0, 0, .54)
  }
  /deep/ .q-field--with-bottom {
    padding 0
  }

  /deep/ .q-field__marginal {
    font-size 16px
    color black
    font-weight 400
    text-align right
  }
  .card-item{
    padding 20px 5px 10px
    .card{
      padding 10px
      box-shadow 0px 0px 7px 0px rgba(22,22,22,0.2)
      border-radius 6px
      transition all 500ms ease-in-out
      -moz-transition all 500ms ease-in-out
      -webkit-transition all 500ms ease-in-out
      -o-transition all 500ms ease-in-out
      position relative
      display block
      cursor pointer
      .bor-b {
        border-bottom 1px solid #D3D3D3
      }
      .device-name{
        max-width calc(100% - 60px)
      }
      .time-box{
        width 120px
        height 34px
        border-radius 17px 2px 17px 17px
        line-height 34px
      }
    }
    .card:hover{
       top -10px
    }
    .card-tips {
      height:24px;
      line-height 24px
      background:rgba(239,241,255,1);
      box-shadow:0px -1px 5px 0px rgba(8,23,109,0.3);
      border-radius:0px 0px 12px 12px;
      padding 0 10px
      img{
        width 16px
        height 16px
      }
      span{
        width calc(100% - 32px)
        padding 0 10px
      }
    }
  }
  .card-item:hover .card{
    top -10px
    background-color #ecefff
  }
  .progress-bar{
    width 100%
    height 14px
    background-color #d3d3d3
    border-radius 4px
    position relative
    margin-top 5px
    .progress-detail {
      height inherit
      background-color $secondary /* 不支持线性的时候显示 */
      background-image linear-gradient(to right, $secondary,#51a8e1, $primary);
      border-radius inherit
    }
    .tips{
      height inherit
      width 2px
      background-color $warning
      position absolute
      top 0
      transition left 200ms ease-in-out
      -moz-transition left 200ms ease-in-out
      -webkit-transition left 200ms ease-in-out
      -o-transition left 200ms ease-in-out
    }
  }
  .warning{
    width 52px
    margin-left 5px
    height 20px
    background rgba(255,0,0,1)
    border-radius 10px
    line-height 20px
    padding 0 5px
  }
  .status {
    width: 10px
    height: 10px
    border-radius: 50%
    display: inline-block
    margin-right 5px
  }
</style>
